const cheerio = require('cheerio')

const galleryPreviewSetParser = (body) => {
  let $ = cheerio.load(body)
  if ($('#gdt .gdtm').length) {
    return normalSizeParser($)
  }
  if ($('#gdt .gdtl').length) {
    return largeSizeParser($)
  }
}

const normalSizeParser = ($) => {
  console.log(2)
}

const largeSizeParser = ($) => {
  var previewSetList = {
    page: null,
    pageLength: null,
    pageNumber: null,
    data: []
  }
  try {
    let page = Number($('table.ptt').find('.ptds').find('a').html())
    if (!page) {
      throw new Error('LARGETHUMBPARSEERROR')
    }
    let pageNumber = Number($('table.ptt').find('td').eq(-2).find('a').html())
    let pageLength = parseInt($('.gtb').find('.gpc').html().split('of')[1])
    $('#gdt .gdtl').each(function (i, elem) {
      let href = $(this).find('a').attr('href')
      previewSetList.data.push({
        href,
        src: $(this).find('a').find('img').attr('src'),
        page: Number(href.split('/')[5].split('-')[1]),
        imgKey: href.split('/')[4]
      })
    })
    previewSetList.page = page
    previewSetList.pageLength = pageLength
    previewSetList.pageNumber = pageNumber
  } catch (err) {
    throw new Error(err.message)
  }
  return previewSetList
}

module.exports = galleryPreviewSetParser
